package com.wayne.sqlSession;

import com.wayne.pojo.Configuration;
import com.wayne.pojo.MappedStatement;
import com.wayne.pojo.SqlCommandType;

import java.lang.reflect.*;
import java.util.Collections;
import java.util.List;

public class DefaultSqlSession implements SqlSession {
  private Configuration configuration;

  public DefaultSqlSession(Configuration configuration) {
    this.configuration = configuration;
  }

  @Override
  public Configuration getConfiguration() {
    return configuration;
  }

  @Override
  public <E> List<E> selectList(String statementId, Object parameter) {
    SimpleExecutor simpleExecutor = new SimpleExecutor();
    MappedStatement mappedStatement = configuration.getMappedStatementMap().get(statementId);
    try {
      return simpleExecutor.query(configuration, mappedStatement, parameter);
    } catch (Exception e) {
      e.printStackTrace();
    }
    return null;
  }

  @Override
  public <T> T selectOne(String statementId, Object parameter) {
    List<Object> objects = selectList(statementId, parameter);
    if (objects.size() == 1) {
      return (T) objects.get(0);
    }
    throw new RuntimeException("查询结果为空或者返回结果过多");
  }

  @Override
  public int delete(String statementId, Object parameter) {
    return doUpdate(statementId, parameter);
  }

  @Override
  public int update(String statementId, Object parameter) {
    return doUpdate(statementId, parameter);
  }

  @Override
  public int insert(String statementId, Object parameter) {
    return doUpdate(statementId, parameter);
  }

  private int doUpdate(String statementId, Object parameter) {
    SimpleExecutor simpleExecutor = new SimpleExecutor();
    MappedStatement mappedStatement = configuration.getMappedStatementMap().get(statementId);
    try {
      return simpleExecutor.update(configuration, mappedStatement, parameter);
    } catch (Exception e) {
      e.printStackTrace();
    }
    return 0;
  }

  @Override
  public <T> T getMapper(Class<T> clazz) {
    return configuration.getMapper(clazz, this);
  }
}
